﻿using Autofac;
using log4net;
using MyWeb.ServiceBus.Services.Impl;
using MyWeb.ServiceBus.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Autofac.Extras.DynamicProxy;

namespace MyWeb.ServiceBus.Extensions.AutofacM
{
    public static class DllFileRegister
    {
        /// <summary>
        /// 注入服务层、仓储层、业务层
        /// </summary>
        /// <param name="builder"></param>
        /// <exception cref="Exception"></exception>
        public static void AddDllFileRegister(this ContainerBuilder builder)
        {
            var basePath = AppContext.BaseDirectory;

            #region 注入服务层、仓储层、业务层
            var servicesDllFile = Path.Combine(basePath, "MyWeb.ServiceBus.Services.dll");

            if (!(File.Exists(servicesDllFile)))
            {
                var msg = "Services.dll 丢失，因为项目解耦了，所以需要先F6编译，再F5运行，请检查 bin 文件夹，并拷贝。";
                throw new Exception(msg);
            }

            builder.RegisterGeneric(typeof(BaseEFService<>)).As(typeof(IBaseService<>)).InstancePerDependency();//注册仓储
            //builder.RegisterGeneric(typeof(BaseSugarService<>)).As(typeof(IBaseService<>)).InstancePerDependency();//注册仓储
            // 获取 Business.dll 程序集服务，并注册
            var assemblysBusiness = Assembly.LoadFrom(servicesDllFile);
            builder.RegisterAssemblyTypes(assemblysBusiness)
                //.Where(t => t.Name.EndsWith("Services"))
                .AsImplementedInterfaces()
                ////.InstancePerRequest()
                .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies)
                .InstancePerDependency()
                .EnableInterfaceInterceptors();       //引用Autofac.Extras.DynamicProxy;
                                                      //.InterceptedBy(cacheType.ToArray()); //允许将拦截器服务的列表分配给注册。


            //builder.RegisterType<UnitOfWorkManage>().As<IUnitOfWorkManage>()
            //    .AsImplementedInterfaces()
            //    .InstancePerLifetimeScope()
            //    .PropertiesAutowired();
            #endregion
        }
    }
}
